package cn.honqun.tinycms.service;

import cn.honqun.tinycms.prop.FileObjectProperties;
import cn.honqun.tinycms.repository.FileObjectMapper;
import cn.honqun.tinycms.service.impl.FileObjectServiceLocal;
import cn.honqun.tinycms.service.impl.FileObjectServiceOSS;
import com.aliyuncs.exceptions.ClientException;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import static cn.honqun.tinycms.prop.FileObjectProperties.STORAGE_OSS;

/**
 * FileObjectService 工厂
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class FileObjectServiceFactory implements FactoryBean<FileObjectService> {
    private final FileObjectMapper fileObjectMapper;
    private final FileObjectProperties fileObjectProperties;
    private final RedissonClient redissonClient;
    private AbstractFileObjectService fileObjectService;

    @PostConstruct
    public void init() throws Exception {
        log.debug("初始化FileObjectService");
        if (STORAGE_OSS.equalsIgnoreCase(fileObjectProperties.getStorage())) {
            log.info("创建OSS FileObjectService");
            fileObjectService = new FileObjectServiceOSS();
            fileObjectService.setFileObjectMapper(fileObjectMapper);
            fileObjectService.setFileObjectProperties(fileObjectProperties);
            fileObjectService.setRedissonClient(redissonClient);
            ((FileObjectServiceOSS) fileObjectService).startup();
        } else {
            log.info("创建Local FileObjectService");
            fileObjectService = new FileObjectServiceLocal();
            fileObjectService.setFileObjectMapper(fileObjectMapper);
            fileObjectService.setFileObjectProperties(fileObjectProperties);
            fileObjectService.setRedissonClient(redissonClient);
        }

    }

    @PreDestroy
    public void shutdown() throws Exception {
        if (STORAGE_OSS.equalsIgnoreCase(fileObjectProperties.getStorage()) && fileObjectService != null) {
            ((FileObjectServiceOSS) fileObjectService).shutdown();
        }
    }

    @Override
    public FileObjectService getObject() throws Exception {
        return fileObjectService;
    }

    @Override
    public Class<?> getObjectType() {
        return FileObjectService.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}
